require "digest/sha2"

class WorkersController < ApplicationController
  before_filter :isSchorsch, :except => [:index, :show, :edit, :update]
  # GET /workers
  # GET /workers.xml
  def index
    @workers = Worker.all :order => "name"

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @workers }
    end
  end

  # GET /workers/1
  # GET /workers/1.xml
  def show
    @worker = Worker.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @worker }
    end
  end

  # GET /workers/new
  # GET /workers/new.xml
  def new
    @worker = Worker.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @worker }
    end
  end

  # GET /workers/1/edit
  def edit
    @worker = Worker.find(params[:id])
    check_hax0r(@worker)
  end

  # POST /workers
  # POST /workers.xml
  def create
    @worker = Worker.new(params[:worker])
    check_hax0r(@worker)
 
    # not so super-random salt ;) should be enough for the bauarbeiters
    @worker.salt = (Digest::SHA2.new << Time.now.to_s + params.values.join(", ") + rand(1024).to_s).to_s
    @worker.password = (Digest::SHA2.new << @worker.salt + @worker.password).to_s 

    respond_to do |format|
      if @worker.save
        format.html { redirect_to(@worker, :notice => 'Worker was successfully created.') }
        format.xml  { render :xml => @worker, :status => :created, :location => @worker }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @worker.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /workers/1
  # PUT /workers/1.xml
  def update
    @worker = Worker.find(params[:id])
    check_hax0r(@worker)

    respond_to do |format|
      if @worker.update_attributes(params[:worker])
        format.html { redirect_to(@worker, :notice => 'Worker was successfully updated.') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @worker.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /workers/1
  # DELETE /workers/1.xml
  def destroy
    @worker = Worker.find(params[:id])
    @worker.destroy

    respond_to do |format|
      format.html { redirect_to(workers_url) }
      format.xml  { head :ok }
    end
  end
private
  def check_hax0r(worker)
    if !@user.is_admin? && !(worker == @user)
      flash[:notice] = "Philip du spack0!"
      redirect_to "/login/logout"
    end
  end

end
